<script lang="ts" setup name="auditOrder">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useSyspurchaseorderApi } from '/@/api/order/syspurchaseorder';
import { useSyssalesorderApi } from '/@/api/order/syssalesorder';
import { useSysreturnorderApi } from '/@/api/order/sysreturnorder';
import { useSyssalesreturnorderApi } from '/@/api/order/syssalesreturnorder';
import { useSysinstockorderApi } from '/@/api/OutWarehou/sysinstockorder';
import { useSysoutstockorderApi } from '/@/api/OutWarehou/sysoutstockorder';
import { useSystransferorderApi } from '/@/api/OutWarehou/systransferorder';
import { useSysstocktakingorderApi } from '/@/api/OutWarehou/sysstocktakingorder';
import warehouseDialog from './component/warehouseDialog.vue';
import outboundDialog from './component/outboundDialog.vue';
import stocktakingDialog from './component/stocktakingDialog.vue';

const purchaseApi = useSyspurchaseorderApi();
const salesApi = useSyssalesorderApi();
const returnApi = useSysreturnorderApi();
const salesReturnApi = useSyssalesreturnorderApi();
const inApi = useSysinstockorderApi();
const outApi = useSysoutstockorderApi();
const transferApi = useSystransferorderApi();
const stockTakingApi = useSysstocktakingorderApi();

// 对话框引用
const warehouseDialogRef = ref();
const outboundDialogRef = ref();
const stocktakingDialogRef = ref();

type ModuleKey = 'purchase'|'sales'|'return'|'salesReturn'|'in'|'out'|'transfer'|'stockTaking';

const state = reactive({
  loading: false,
  tableData: [] as any[],
  selectData: [] as any[],
  params: { page: 1, pageSize: 20 },
  filters: { keyword: '', module: '' as ModuleKey | '' , status: undefined as number|string|undefined },
  statistics: {
    total: 0,
    pending: 0,
    approved: 0,
    rejected: 0,
    draft: 0
  }
});

const moduleOptions: { label: string; value: ModuleKey }[] = [
  { label: '进货订单', value: 'purchase' },
  { label: '销售订单', value: 'sales' },
  { label: '退货订单', value: 'return' },
  { label: '销售退货', value: 'salesReturn' },
  { label: '调拨单', value: 'transfer' },
  { label: '盘点单', value: 'stockTaking' },
];

const fetchers: Record<ModuleKey, (p:any)=>Promise<any>> = {
  purchase: (p)=>purchaseApi.page(p),
  sales: (p)=>salesApi.page(p),
  return: (p)=>returnApi.page(p),
  salesReturn: (p)=>salesReturnApi.page(p),
  in: (p)=>inApi.page(p),
  out: (p)=>outApi.page(p),
  transfer: (p)=>transferApi.page(p),
  stockTaking: (p)=>stockTakingApi.page(p),
};

// 统一的状态更新，优先调用 setStatus；没有则回退到 update
const updateStatus = async (module: ModuleKey, id: number, documentStatus: number | string) => {
  const api: any = {
    purchase: purchaseApi,
    sales: salesApi,
    return: returnApi,
    salesReturn: salesReturnApi,
    in: inApi,
    out: outApi,
    transfer: transferApi,
    stockTaking: stockTakingApi,
  }[module];
  if (!api) return;
  
  if (typeof api.setStatus === 'function') {
    // 如果有专门的 setStatus 接口，使用它
    await api.setStatus({ id, status: documentStatus });
  } else if (typeof api.update === 'function') {
    // 否则需要获取完整订单数据再更新
    try {
      // 1. 获取订单的完整详情
      const detailRes = await api.detail(id);
      const orderDetail = detailRes.data.result;

      if (!orderDetail) {
        ElMessage.error('未找到订单详情，无法更新状态！');
        return;
      }

      // 2. 更新订单状态
      orderDetail.documentStatus = documentStatus;

      // 3. 将完整的订单对象发送给后端进行更新
      await api.update(orderDetail);
    } catch (error: any) {
      console.error('更新订单状态失败:', error);
      ElMessage.error('更新订单状态失败：' + (error.message || '未知错误'));
      throw error;
    }
  }
};

const handleQuery = async () => {
  if (!state.filters.module) {
    ElMessage.warning('请选择模块');
    return;
  }
  state.loading = true;
  try {
    const api = fetchers[state.filters.module as ModuleKey];
    const params:any = { ...state.params };
    if (state.filters.keyword) params.keyword = state.filters.keyword;
    
    // 根据模块类型处理状态查询
    if (state.filters.status != null) {
      if (state.filters.module === 'purchase') {
        // 进货订单使用中文状态
        const statusMap: { [key: number]: string } = {
          1: '草稿',
          2: '待审核', 
          3: '驳回',
          4: '未入库',
          6: '已完成',
          7: '已关闭'
        };
        params.documentStatus = (typeof state.filters.status === 'number' ? statusMap[state.filters.status] : '') || '';
      } else {
        // 其他模块使用数字状态
        params.documentStatus = state.filters.status;
      }
    }
    
    const res = await api(params);
    const result = res?.data?.result;
    state.tableData = result?.items || result || [];
    
    // 计算统计信息
    calculateStatistics();
  } finally {
    state.loading = false;
  }
};

// 计算统计信息
const calculateStatistics = () => {
  const stats = {
    total: state.tableData.length,
    pending: 0,
    approved: 0,
    rejected: 0,
    draft: 0
  };
  
  state.tableData.forEach(row => {
    const status = String(row.documentStatus);
    if (isPendingStatus(status)) {
      stats.pending++;
    } else if (status === '6' || status === '已完成') {
      stats.approved++;
    } else if (status === '3' || status === '驳回') {
      stats.rejected++;
    } else if (status === '1' || status === '草稿') {
      stats.draft++;
    }
  });
  
  state.statistics = stats;
};

const approve = async (rows: any[]) => {
  if (!rows.length) return ElMessage.warning('请先选择记录');
  
  // 过滤出待审核的订单
  const pendingRows = rows.filter(row => isPendingStatus(row.documentStatus));
  if (!pendingRows.length) {
    return ElMessage.warning('所选订单中没有待审核状态的订单');
  }
  
  await ElMessageBox.confirm(`确认审核通过选中的 ${pendingRows.length} 条待审核记录吗？`, '批量审核通过');
  const module = state.filters.module as ModuleKey;
  
  try {
    // 根据模块类型使用正确的状态值
    // 审核通过后设置为未入库/未出库状态，等待出入库操作
    let approvedStatus;
    if (module === 'purchase') {
      approvedStatus = '未入库'; // 采购订单审核通过后为未入库
    } else if (module === 'sales') {
      approvedStatus = 4; // 销售订单审核通过后为未出库
    } else if (module === 'return') {
      approvedStatus = 4; // 进货退货审核通过后为未入库
    } else if (module === 'salesReturn') {
      approvedStatus = 4; // 销售退货审核通过后为未入库
    } else {
      approvedStatus = 4; // 其他订单默认为未出库/未入库
    }
    
    await Promise.all(pendingRows.map(r => updateStatus(module, r.id, approvedStatus)));
    
    ElMessage.success(`成功审核通过 ${pendingRows.length} 条订单，状态已更新为未入库/未出库`);
    await handleQuery();
  } catch (error) {
    ElMessage.error('批量审核操作失败，请重试');
  }
};

const reject = async (rows: any[]) => {
  if (!rows.length) return ElMessage.warning('请先选择记录');
  
  // 过滤出待审核的订单
  const pendingRows = rows.filter(row => isPendingStatus(row.documentStatus));
  if (!pendingRows.length) {
    return ElMessage.warning('所选订单中没有待审核状态的订单');
  }
  
  await ElMessageBox.confirm(`确认驳回选中的 ${pendingRows.length} 条待审核记录吗？`, '批量驳回');
  const module = state.filters.module as ModuleKey;
  
  try {
    // 根据模块类型使用正确的状态值
    const rejectedStatus = module === 'purchase' ? '驳回' : 3;
    await Promise.all(pendingRows.map(r => updateStatus(module, r.id, rejectedStatus)));
    
    ElMessage.success(`成功驳回 ${pendingRows.length} 条订单`);
    await handleQuery();
  } catch (error) {
    ElMessage.error('批量驳回操作失败，请重试');
  }
};

// 批量出入库操作
const warehouseApprove = async (rows: any[]) => {
  if (!rows.length) return ElMessage.warning('请先选择记录');
  
  // 过滤出未入库/未出库的订单
  const warehouseRows = rows.filter(row => {
    const status = String(row.documentStatus);
    return status === '4' || status === '未入库' || status === '未出库';
  });
  
  if (!warehouseRows.length) {
    return ElMessage.warning('所选订单中没有未入库/未出库状态的订单');
  }
  
  const module = state.filters.module as ModuleKey;
  const operationType = module === 'in' ? '入库' : module === 'out' ? '出库' : '出入库';
  
  await ElMessageBox.confirm(`确认对选中的 ${warehouseRows.length} 条未入库/未出库订单进行${operationType}操作吗？`, `${operationType}操作`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  });
  
  try {
    // 直接设置为已完成状态
    const completedStatus = module === 'purchase' ? '已完成' : 6;
    await Promise.all(warehouseRows.map(r => updateStatus(module, r.id, completedStatus)));
    
    ElMessage.success(`成功完成 ${warehouseRows.length} 条订单的${operationType}操作，状态已更新为已完成`);
    await handleQuery();
  } catch (error) {
    ElMessage.error(`${operationType}操作失败，请重试`);
  }
};

// 判断是否为待审核状态（包括待审核和未出库/未入库状态）
const isPendingStatus = (status: any) => {
  const pendingStatuses = ['2', 'PendingReview', '待审核', '4', '未入库', '未出库'];
  return pendingStatuses.includes(String(status));
};

// 判断是否为待审核状态（仅限待审核）
const isPendingReviewStatus = (status: any) => {
  const pendingStatuses = ['2', 'PendingReview', '待审核'];
  return pendingStatuses.includes(String(status));
};

// 判断是否为出入库状态
const isWarehouseStatus = (status: any) => {
  const warehouseStatuses = ['4', '未入库', '未出库', '未调拨', '未盘点'];
  return warehouseStatuses.includes(String(status));
};

// 获取出入库按钮文本
const getWarehouseButtonText = (status: any) => {
  const statusStr = String(status);
  const module = state.filters.module as ModuleKey;
  
  if (statusStr === '未入库' || (statusStr === '4' && (module === 'in' || module === 'purchase' || module === 'return' || module === 'salesReturn'))) {
    return '入库';
  } else if (statusStr === '未出库' || (statusStr === '4' && (module === 'out' || module === 'sales'))) {
    return '出库';
  } else if (statusStr === '未调拨' || (statusStr === '4' && module === 'transfer')) {
    return '调拨';
  } else if (statusStr === '未盘点' || (statusStr === '4' && module === 'stockTaking')) {
    return '盘点';
  } else {
    return '操作';
  }
};

// 处理入库确认
const handleWarehouseConfirm = async (formData: any) => {
  try {
    const module = state.filters.module as ModuleKey;
    const completedStatus = module === 'purchase' ? '已完成' : 6;
    
    // 更新订单状态为已完成
    await updateStatus(module, formData.orderId, completedStatus);
    
    ElMessage.success(`订单 "${formData.orderCode}" 入库操作成功，状态已更新为已完成`);
    await handleQuery();
  } catch (error) {
    console.error('更新订单状态失败:', error);
    ElMessage.error('更新订单状态失败');
  }
};

// 处理出库确认
const handleOutboundConfirm = async (formData: any) => {
  try {
    const module = state.filters.module as ModuleKey;
    const completedStatus = module === 'purchase' ? '已完成' : 6;
    
    // 更新订单状态为已完成
    await updateStatus(module, formData.orderId, completedStatus);
    
    ElMessage.success(`订单 "${formData.orderCode}" 出库操作成功，状态已更新为已完成`);
    await handleQuery();
  } catch (error) {
    console.error('更新订单状态失败:', error);
    ElMessage.error('更新订单状态失败');
  }
};

// 处理盘点确认
const handleStocktakingConfirm = async () => {
  // 盘点对话框已经处理了所有逻辑，这里只需要刷新列表
  await handleQuery();
};

// 单个订单出入库操作
const warehouseApproveSingle = async (row: any) => {
  const statusStr = String(row.documentStatus);
  const module = state.filters.module as ModuleKey;
  
  // 根据状态和模块类型打开相应的对话框
  if (statusStr === '未入库' || (statusStr === '4' && (module === 'in' || module === 'purchase' || module === 'return' || module === 'salesReturn'))) {
    // 打开入库对话框
    warehouseDialogRef.value?.openDialog(row);
  } else if (statusStr === '未出库' || (statusStr === '4' && (module === 'out' || module === 'sales'))) {
    // 打开出库对话框
    outboundDialogRef.value?.openDialog(row);
  } else if (statusStr === '未调拨' || (statusStr === '4' && module === 'transfer')) {
    // 调拨操作：更新单据状态、出库状态、入库状态为已完成
    try {
      await ElMessageBox.confirm(`确认完成调拨操作吗？`, '调拨确认', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      });
      
      // 获取调拨单完整详情
      const detailRes = await transferApi.detail(row.id);
      const orderDetail = detailRes.data.result;
      
      console.log('调拨单详情（更新前）:', orderDetail);
      
      if (!orderDetail) {
        ElMessage.error('未找到调拨单详情，无法更新状态！');
        return;
      }
      
      // 更新单据状态、出库状态、入库状态为已完成
      orderDetail.documentStatus = 6; // 已完成
      orderDetail.outStatus = 6; // 出库状态：已完成
      orderDetail.inStatus = 6; // 入库状态：已完成
      
      console.log('调拨单数据（准备更新）:', {
        id: orderDetail.id,
        code: orderDetail.code,
        documentStatus: orderDetail.documentStatus,
        outStatus: orderDetail.outStatus,
        inStatus: orderDetail.inStatus
      });
      
      // 将完整的订单对象发送给后端进行更新
      await transferApi.update(orderDetail);
      
      console.log('调拨单更新成功');
      
      ElMessage.success(`调拨单 "${row.code}" 调拨操作成功，单据状态、出库状态、入库状态已更新为已完成`);
      await handleQuery();
    } catch (error: any) {
      if (error !== 'cancel') {
        console.error('调拨操作失败:', error);
        ElMessage.error('调拨操作失败：' + (error.message || '未知错误'));
      }
    }
  } else if (statusStr === '未盘点' || (statusStr === '4' && module === 'stockTaking')) {
    // 打开盘点对话框
    stocktakingDialogRef.value?.openDialog(row);
  } else {
    ElMessage.warning('当前订单状态不支持出入库操作');
  }
};

// 单个订单审核通过
const approveSingle = async (row: any) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入审批意见：', '审核通过', {
      confirmButtonText: '确认通过',
      cancelButtonText: '取消',
      inputType: 'textarea',
      inputPlaceholder: '请输入审批意见...',
    });
    
    const comment = value || '审核通过';
    const module = state.filters.module as ModuleKey;
    const currentStatus = String(row.documentStatus);
    
    // 根据当前状态和模块类型确定审核后的状态
    let approvedStatus;
    if (currentStatus === '2' || currentStatus === 'PendingReview' || currentStatus === '待审核') {
      // 待审核状态审核通过后，根据模块类型设置为未入库/未出库
      if (module === 'purchase') {
        approvedStatus = '未入库';
      } else if (module === 'sales') {
        approvedStatus = 4; // 未出库
      } else if (module === 'return') {
        approvedStatus = 4; // 未入库
      } else if (module === 'salesReturn') {
        approvedStatus = 4; // 未入库
      } else {
        approvedStatus = 4; // 默认未出库/未入库
      }
    } else if (currentStatus === '4' || currentStatus === '未入库' || currentStatus === '未出库') {
      // 未出库/未入库状态审核通过后设置为已完成
      approvedStatus = module === 'purchase' ? '已完成' : 6;
    } else {
      // 其他状态直接设置为已完成
      approvedStatus = module === 'purchase' ? '已完成' : 6;
    }
    
    await updateStatus(module, row.id, approvedStatus);
    
    ElMessage.success(`订单 "${row.code}" 审核通过成功`);
    await handleQuery();
  } catch (error) {
    // 用户取消操作
  }
};

// 单个订单驳回
const rejectSingle = async (row: any) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入驳回原因：', '驳回订单', {
      confirmButtonText: '确认驳回',
      cancelButtonText: '取消',
      inputType: 'textarea',
      inputPlaceholder: '请输入驳回原因...',
    });
    
    const comment = value || '订单驳回';
    const module = state.filters.module as ModuleKey;
    
    // 根据模块类型使用正确的状态值
    const rejectedStatus = module === 'purchase' ? '驳回' : 3;
    await updateStatus(module, row.id, rejectedStatus);
    
    ElMessage.success(`订单 "${row.code}" 驳回成功`);
    await handleQuery();
  } catch (error) {
    // 用户取消操作
  }
};


// 查看订单详情
const viewOrderDetail = (row: any) => {
  const statusInfo = getStatusInfo(row.documentStatus);
  const goodsDisplay = row.goodsNameDisplay || row.goodsName || '未设置';
  const warehouseDisplay = row.warehouseNameDisplay || row.fromWarehouseDisplay || row.toWarehouseDisplay || row.warehouseName || '未设置';
  
  ElMessageBox.alert(`
    <div style="text-align: left;">
      <h3>订单详情</h3>
      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin: 20px 0;">
        <div>
          <p><strong>订单编号：</strong>${row.code}</p>
          <p><strong>货品名称：</strong>${goodsDisplay}</p>
          <p><strong>仓库/部门：</strong>${warehouseDisplay}</p>
          <p><strong>制单人：</strong>${row.createUserName}</p>
        </div>
        <div>
          <p><strong>制单时间：</strong>${row.createTime}</p>
          <p><strong>更新时间：</strong>${row.updateTime || '无'}</p>
          <p><strong>订单状态：</strong><span style="color: ${getStatusColor(statusInfo.type)}">${statusInfo.text}</span></p>
          <p><strong>租户ID：</strong>${row.tenantId || '无'}</p>
        </div>
      </div>
      <hr>
      <h4>详细信息</h4>
      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
        <div>
          <p><strong>货品数量：</strong>${row.itemQuantity || row.salesQuantity || row.quantity || '无'}</p>
          <p><strong>货品金额：</strong>${row.itemAmount || row.salesAmount || row.transferAmount || '无'}</p>
          <p><strong>供应商/客户：</strong>${row.supplier || row.customerName || '无'}</p>
        </div>
        <div>
          <p><strong>联系人：</strong>${row.contactPerson || '无'}</p>
          <p><strong>联系方式：</strong>${row.contactMethod || '无'}</p>
          <p><strong>部门ID：</strong>${row.purchaseDeptId || row.salesDeptId || '无'}</p>
        </div>
      </div>
      <hr>
      <h4>备注信息</h4>
      <p style="background: #f5f5f5; padding: 10px; border-radius: 4px; margin: 0;">${row.remark || '无备注信息'}</p>
    </div>
  `, '订单详情', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '关闭',
    customStyle: { width: '600px' }
  } as any);
};

// 获取状态颜色
const getStatusColor = (type: string) => {
  const colorMap: { [key: string]: string } = {
    'success': '#67c23a',
    'warning': '#e6a23c', 
    'danger': '#f56c6c',
    'info': '#909399'
  };
  return colorMap[type] || '#909399';
};

// 获取状态标签类型和文本
const getStatusInfo = (status: any) => {
  const statusStr = String(status);
  const module = state.filters.module as ModuleKey;
  
  // 根据模块类型确定状态4的显示文本
  let status4Text = '未出/未入';
  if (module === 'purchase' || module === 'in' || module === 'return' || module === 'salesReturn') {
    status4Text = '未入库';
  } else if (module === 'sales' || module === 'out') {
    status4Text = '未出库';
  } else if (module === 'transfer') {
    status4Text = '未调拨';
  } else if (module === 'stockTaking') {
    status4Text = '未盘点';
  }
  
  const statusMap: { [key: string]: { type: string; text: string } } = {
    // 数字状态码
    '1': { type: 'info', text: '草稿' },
    '2': { type: 'warning', text: '待审核' },
    '3': { type: 'danger', text: '驳回' },
    '4': { type: 'warning', text: status4Text },
    '6': { type: 'success', text: '已完成' },
    '7': { type: 'info', text: '已关闭' },
    // 枚举状态码
    'Draft': { type: 'info', text: '草稿' },
    'PendingReview': { type: 'warning', text: '待审核' },
    'Rejected': { type: 'danger', text: '驳回' },
    'NotOutOfWarehouse': { type: 'warning', text: status4Text },
    'Completed': { type: 'success', text: '已完成' },
    'Closed': { type: 'info', text: '已关闭' },
    // 中文状态值（进货订单等使用）
    '草稿': { type: 'info', text: '草稿' },
    '待审核': { type: 'warning', text: '待审核' },
    '驳回': { type: 'danger', text: '驳回' },
    '未入库': { type: 'warning', text: '未入库' },
    '已完成': { type: 'success', text: '已完成' },
    '已关闭': { type: 'info', text: '已关闭' },
    '未出库': { type: 'warning', text: '未出库' },
  };
  return statusMap[statusStr] || { type: 'info', text: '未知' };
};

onMounted(handleQuery);
</script>

<template>
  <div class="g-container">
    <el-card shadow="hover">
      <el-form :inline="true">
        <el-form-item label="模块">
          <el-select 
            v-model="state.filters.module" 
            placeholder="请选择模块" 
            style="width:180px"
            popper-append-to-body
            :popper-options="{ strategy: 'fixed' }"
          >
            <el-option v-for="opt in moduleOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="state.filters.status" 
            placeholder="全部" 
            clearable 
            style="width:160px"
            popper-append-to-body
            :popper-options="{ strategy: 'fixed' }"
          >
            <template v-if="state.filters.module === 'purchase'">
              <el-option label="草稿" value="草稿" />
              <el-option label="待审核" value="待审核" />
              <el-option label="驳回" value="驳回" />
              <el-option label="未入库" value="未入库" />
              <el-option label="已完成" value="已完成" />
             
            </template>
            <template v-else-if="state.filters.module === 'sales'">
              <el-option label="草稿" :value="1" />
              <el-option label="待审核" :value="2" />
              <el-option label="驳回" :value="3" />
              <el-option label="未出库" :value="4" />
              <el-option label="已完成" :value="6" />
            
            </template>
            <template v-else-if="state.filters.module === 'return'">
              <el-option label="草稿" :value="1" />
              <el-option label="待审核" :value="2" />
              <el-option label="驳回" :value="3" />
              <el-option label="未入库" :value="4" />
              <el-option label="已完成" :value="6" />
             
            </template>
            <template v-else-if="state.filters.module === 'salesReturn'">
              <el-option label="草稿" :value="1" />
              <el-option label="待审核" :value="2" />
              <el-option label="驳回" :value="3" />
              <el-option label="未入库" :value="4" />
              <el-option label="已完成" :value="6" />
             
            </template>
            <template v-else-if="state.filters.module === 'transfer'">
              <el-option label="草稿" :value="1" />
              <el-option label="待审核" :value="2" />
              <el-option label="驳回" :value="3" />
              <el-option label="未调拨" :value="4" />
              <el-option label="已完成" :value="6" />
              <el-option label="已关闭" :value="7" />
            </template>
            <template v-else-if="state.filters.module === 'stockTaking'">
              <el-option label="草稿" :value="1" />
              <el-option label="待审核" :value="2" />
              <el-option label="驳回" :value="3" />
              <el-option label="未盘点" :value="4" />
              <el-option label="已完成" :value="6" />
              <el-option label="已关闭" :value="7" />
            </template>
            <template v-else>
              <el-option label="草稿" :value="1" />
              <el-option label="待审核" :value="2" />
              <el-option label="驳回" :value="3" />
              <el-option label="未出/未入" :value="4" />
              <el-option label="已完成" :value="6" />
              <el-option label="已关闭" :value="7" />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="state.filters.keyword" placeholder="单号/仓库/客户/货品/备注..." style="width:260px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="success" @click="approve(state.selectData)" :disabled="!state.selectData.length">审核通过</el-button>
          <el-button type="danger" @click="reject(state.selectData)" :disabled="!state.selectData.length">驳回</el-button>
          <el-button type="warning" @click="warehouseApprove(state.selectData)" :disabled="!state.selectData.length">出入库操作</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息卡片 -->
    <el-card shadow="hover" style="margin-top: 5px" v-if="state.filters.module">
      <template #header>
        <span>订单统计</span>
      </template>
      <div style="display: flex; gap: 30px; align-items: center;">
        <div style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #409eff;">{{ state.statistics.total }}</div>
          <div style="color: #666; font-size: 12px;">总订单</div>
        </div>
        <div style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #e6a23c;">{{ state.statistics.pending }}</div>
          <div style="color: #666; font-size: 12px;">待审核</div>
        </div>
        <div style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #67c23a;">{{ state.statistics.approved }}</div>
          <div style="color: #666; font-size: 12px;">已完成</div>
        </div>
        <div style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #f56c6c;">{{ state.statistics.rejected }}</div>
          <div style="color: #666; font-size: 12px;">已驳回</div>
        </div>
        <div style="text-align: center;">
          <div style="font-size: 24px; font-weight: bold; color: #909399;">{{ state.statistics.draft }}</div>
          <div style="color: #666; font-size: 12px;">草稿</div>
        </div>
      </div>
    </el-card>

    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <!-- 调拨单模块显示详细表格 -->
      <el-table v-if="state.filters.module === 'transfer'" :data="state.tableData" v-loading="state.loading" @selection-change="(val:any[])=>state.selectData=val" row-key="id" border>
        <el-table-column type="selection" width="40" />
        <el-table-column prop="code" label="调拨单号" width="160" show-overflow-tooltip />
        <el-table-column label="单据状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusInfo(row.documentStatus).type" size="small">
              {{ getStatusInfo(row.documentStatus).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyDate" label="调拨申请日期" width="160" show-overflow-tooltip />
        <el-table-column label="调出仓库" width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.fromWarehouseDisplay || row.fromWarehouse || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="调入仓库" width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.toWarehouseDisplay || row.toWarehouse || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="出库状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusInfo(row.outStatus).type" size="small">
              {{ getStatusInfo(row.outStatus).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入库状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusInfo(row.inStatus).type" size="small">
              {{ getStatusInfo(row.inStatus).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="transferQuantity" label="调拨数量" width="100" />
        <el-table-column prop="transferAmount" label="调拨金额" width="100" />
        <el-table-column prop="agentName" label="经办人" width="120" />
        <el-table-column label="调拨货品" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.goodsNameDisplay || row.goodsName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <!-- 待审核状态显示审核按钮 -->
            <template v-if="isPendingReviewStatus(row.documentStatus)">
              <el-button type="success" size="small" @click="approveSingle(row)">审核通过</el-button>
              <el-button type="danger" size="small" @click="rejectSingle(row)">驳回</el-button>
            </template>
            <!-- 未调拨状态显示调拨按钮 -->
            <template v-else-if="isWarehouseStatus(row.documentStatus)">
              <el-button type="warning" size="small" @click="warehouseApproveSingle(row)">
                调拨
              </el-button>
            </template>
            <!-- 其他状态显示查看按钮 -->
            <template v-else>
              <el-button size="small" @click="viewOrderDetail(row)">查看详情</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 盘点单模块显示详细表格 -->
      <el-table v-else-if="state.filters.module === 'stockTaking'" :data="state.tableData" v-loading="state.loading" @selection-change="(val:any[])=>state.selectData=val" row-key="id" border>
        <el-table-column type="selection" width="40" />
        <el-table-column prop="code" label="盘点单号" width="160" show-overflow-tooltip />
        <el-table-column label="盘点结果" width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag v-if="row.inventoryResult === 'surplus'" type="success" size="small">盘盈</el-tag>
            <el-tag v-else-if="row.inventoryResult === 'loss'" type="danger" size="small">盘亏</el-tag>
            <el-tag v-else-if="row.inventoryResult === 'match'" type="info" size="small">账实相符</el-tag>
            <span v-else>{{ row.inventoryResult || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="仓库名称" width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.warehouseNameDisplay || row.warehouseName || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="盘点类型" width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.stockTakingType === 'inventory'">存货盘点</span>
            <span v-else-if="row.stockTakingType === 'periodEnd'">期末盘点</span>
            <span v-else-if="row.stockTakingType === 'periodStart'">期初盘点</span>
            <span v-else>{{ row.stockTakingType || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="盘点开始时间" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.startTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="盘点结束时间" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.endTime || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="出库状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusInfo(row.outStatus).type" size="small">
              {{ getStatusInfo(row.outStatus).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入库状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusInfo(row.inStatus).type" size="small">
              {{ getStatusInfo(row.inStatus).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="盘点货品" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.goodsNameDisplay || row.goodsName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="盘点数量" width="100" />
        <el-table-column prop="profitQuantity" label="盘盈数量" width="100">
          <template #default="{ row }">
            <span style="color: #67c23a; font-weight: bold;">{{ row.profitQuantity || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="profitAmount" label="盘盈金额" width="100">
          <template #default="{ row }">
            <span style="color: #67c23a; font-weight: bold;">{{ row.profitAmount || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lossQuantity" label="盘亏数量" width="100">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: bold;">{{ row.lossQuantity || 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <!-- 待审核状态显示审核按钮 -->
            <template v-if="isPendingReviewStatus(row.documentStatus)">
              <el-button type="success" size="small" @click="approveSingle(row)">审核通过</el-button>
              <el-button type="danger" size="small" @click="rejectSingle(row)">驳回</el-button>
            </template>
            <!-- 未盘点状态显示盘点按钮 -->
            <template v-else-if="isWarehouseStatus(row.documentStatus)">
              <el-button type="warning" size="small" @click="warehouseApproveSingle(row)">
                盘点
              </el-button>
            </template>
            <!-- 其他状态显示查看按钮 -->
            <template v-else>
              <el-button size="small" @click="viewOrderDetail(row)">查看详情</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 其他模块显示简化表格 -->
      <el-table v-else :data="state.tableData" v-loading="state.loading" @selection-change="(val:any[])=>state.selectData=val" row-key="id" border>
        <el-table-column type="selection" width="40" />
        <el-table-column prop="code" label="单号" width="160" />
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusInfo(row.documentStatus).type" size="small">
              {{ getStatusInfo(row.documentStatus).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="货品" min-width="220" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.goodsNameDisplay || row.goodsName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="warehouseName" label="仓库/部门" width="160" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.warehouseNameDisplay || row.fromWarehouseDisplay || row.toWarehouseDisplay || row.warehouseName || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createUserName" label="制单人" width="120" />
        <el-table-column prop="createTime" label="制单时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <!-- 待审核状态显示审核按钮 -->
            <template v-if="isPendingReviewStatus(row.documentStatus)">
              <el-button type="success" size="small" @click="approveSingle(row)">审核通过</el-button>
              <el-button type="danger" size="small" @click="rejectSingle(row)">驳回</el-button>
            </template>
            <!-- 未入库/未出库状态显示出入库按钮 -->
            <template v-else-if="isWarehouseStatus(row.documentStatus)">
              <el-button type="warning" size="small" @click="warehouseApproveSingle(row)">
                {{ getWarehouseButtonText(row.documentStatus) }}
              </el-button>
            </template>
            <!-- 其他状态显示查看按钮 -->
            <template v-else>
              <el-button size="small" @click="viewOrderDetail(row)">查看详情</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 入库操作对话框 -->
    <warehouseDialog ref="warehouseDialogRef" @confirm="handleWarehouseConfirm" @cancel="() => {}" />
    
    <!-- 出库操作对话框 -->
    <outboundDialog ref="outboundDialogRef" @confirm="handleOutboundConfirm" @cancel="() => {}" />
    
    <!-- 盘点操作对话框 -->
    <stocktakingDialog ref="stocktakingDialogRef" @confirm="handleStocktakingConfirm" @cancel="() => {}" />
  </div>
</template>

<style scoped>
.g-container { 
  padding: 10px; 
}

/* 确保下拉框选项显示在最上层 */
:deep(.el-select-dropdown) {
  z-index: 3000 !important;
}

:deep(.el-popper) {
  z-index: 3000 !important;
}
</style>
